/*
 * @brief
 * std::timed_mutex比std::mutex多了两个超时获取锁的接口：try_lock_for和try_lock_until
 * @note
 * 1. try_lock_for   尝试获取互斥锁。阻塞直到指定timeout_duration时间过去或获得锁
 * 2. try_lock_until 尝试获取互斥锁。阻塞直到timeout_time达到指定或获得锁
 */

#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>

std::timed_mutex mutex;

void work() {
    std::chrono::milliseconds timeout(100);
    while (true) {
        if (mutex.try_lock_for(timeout)) {
            std::cout << "threadId [" << std::this_thread::get_id() << "] "
                      << "work with the mutex" << std::endl;
            std::chrono::milliseconds sleepDuration(250);
            std::this_thread::sleep_for(sleepDuration);
            mutex.unlock();
            std::this_thread::sleep_for(sleepDuration);
        } else {
            std::cout << "threadId [" << std::this_thread::get_id() << "] "
                      << "work without the mutex" << std::endl;
            std::chrono::milliseconds sleepDuration(100);
            std::this_thread::sleep_for(sleepDuration);
        }
    }
}

int main(void) {
    std::thread t1(work);
    std::thread t2(work);
    t1.join();
    t2.join();
    std::cout << "main finish\n";
    return 0;
}